package com.zcbl.toolkit.aliyun.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Proxy;

/**
 * @author he peng
 * @create 2018/4/26 11:49
 * @see
 */

@Configuration
@EnableConfigurationProperties(OSSProperties.class)
@ConditionalOnClass(OSSClient.class)
@ConditionalOnProperty(
        prefix = "aliyun.oss" ,
        name = {
                "external-endpoint" , "internal-endpoint" , "access-key-id" ,
                "access-key-secret" , "bucket"})
public class OSSAutoConfiguration {

    @Autowired
    @Bean
    public OSSEnhance ossEnhance(OSSProperties ossProperties) {
        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        OSSClient ossClient = new OSSClient(ossProperties.getExternalEndpoint(), credentialProvider, null);
        DefaultOSSEnhanceClient defaultOssEnhanceClient = new DefaultOSSEnhanceClient(
                ossProperties.getExternalEndpoint(), credentialProvider, null, ossProperties ,ossClient);
        OSSEnhance ossEnhance = (OSSEnhance) Proxy.newProxyInstance(defaultOssEnhanceClient.getClass().getClassLoader(),
                defaultOssEnhanceClient.getClass().getInterfaces(), defaultOssEnhanceClient);
        return ossEnhance;
    }
}
